import React, { forwardRef, useImperativeHandle, useRef } from "react";

interface RefProps {
  focus: () => void;
}
const MyInput = forwardRef<RefProps>((props, ref) => {
  const realInputRef = useRef<HTMLInputElement>(null);
  useImperativeHandle(
    ref,
    () => ({
      focus() {
        realInputRef.current?.focus();
      }
    }),
    []
  );

  return <input {...props} ref={realInputRef} />;
});

const MyForm: React.FC = () => {
  const inputRef = useRef<RefProps>(null);

  function handleClick() {
    inputRef.current?.focus();
  }

  return (
    <>
      <MyInput ref={inputRef} />
      <button onClick={handleClick}>聚焦输入框</button>
    </>
  );
};
export default MyForm;
